<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*******************
***  wish订单同步处理
***  
*** 2017/06/3
**********/
class Wishdata_Remote
{
	
	function __construct()
	{    
		 $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
        $this->db2 = $this->CI->load->database('amazondata', TRUE);
		$this->CI->load->library('Amazondata');
        $this->amazondata=new amazondata();
	}
	

	function getinsertdata()
	{
		$this->db2->limit(1);
		$row = $this->db2->get_where("db_wish_order_list","syntype=1  ")->result_array();
		
		if(count($row)==0)
		{
			return false;
		}
		$rs = $row[0];
		
		$rorder = $this->db1->get_where("db_order_list","tradeid='".$rs["tradeid"]."' AND shopid='".$rs["shopid"]."'")->result_array();
		if($rorder[0]["order_id"])
		{
			$this->db2->update("db_wish_order_list",array("syntype"=>2,"descr"=>'已同步系统成功'),"tradeid='".$rs["tradeid"]."' ");
			return $this->getinsertdata();
		}
		$exchange=$this->db1->get_where("d_moneyrate","name='".$rs["moneytype"]."'")->result_array();
		$exchangerate=$exchange[0]["rate"]; 
			
			$postdata="";
			$postdata["order_sn"] = $this->amazondata->getNo('wish');
			$postdata["dates"] = date("Y-m-d");
			$postdata["order_status"] =2;
			$postdata["order_source"] ='正常订单';
			$postdata['shipping_status']=0;
			$postdata["customerid"] =$rs['customerid']?$rs['customerid']:$rs['consignee'];
			$postdata["consignee"] =$rs['consignee'];
			$postdata["country"] = $rs['country'];
			
			$rscountry = $this->db1->get_where("d_chinaexpress","NAME='".$rs['country']."'")->result_array();
			if($rscountry[0]["id"]){
				$postdata["country_cn"] = $rscountry[0]["FILED1"];
			}
			

			$postdata["province"] = $rs['province'];
			$postdata["city"] = $rs['city'];
			
			$postdata["address"] =$rs['address'];
			// $postdata["address2"] = '';
			$postdata["zipcode"] = $rs['zipcode'];
			//$postdata["tel"] = $info['37']?$info['37']:0;
			$postdata["mobile"] = $rs['mobile'];
			$postdata["country_code"] = $rs['country_code'];
			$postdata["email"] = '';
			$postdata["shopid"] = $rs["shopid"];
			$rshop = $this->db1->get_where("d_shop","id=".$rs["shopid"])->result_array();
			$postdata["shopname"] = $rs["shopname"];
			$postdata["shopoper"] = $rshop[0]["updateoper"];

			if($rshop[0]["shop_platform_fee"]>0)
			{
				$shop_platform_fee  =$rshop[0]["shop_platform_fee"];
			}else{
				$shop_platform_fee = 0.15;
			}
			if($rshop[0]["shop_pay_fee"]>0)
			{
				$shop_pay_fee  =$rshop[0]["shop_pay_fee"];
			}else{
				$shop_pay_fee = 0.015;
			}

			$postdata["moneytype"] ='USD';
			$postdata["tradeid"] = $rs["tradeid"];
			$postdata["goods_originask"] = $rs['goods_originask'];
			$postdata["goods_amount"] =$rs['goods_originask']*$exchangerate;
			$postdata["shipping_fee"] = $rs['shipping_fee']*$exchangerate;
			$postdata["shipping_originask"] = $rs['shipping_originask'];
			$postdata["add_time"] = time();
			$postdata["ordertime"] = $rs['ordertime'];
			$postdata["payid"] = $rs['payid'];
			$postdata["saleschannel"] = 'wish';
			$postdata["pay_fee"] = $rs['goods_originask']*$shop_pay_fee*$exchangerate;
			$postdata['pack_fee']='';
			$postdata["platform_fee"] = $rs['goods_originask']*$shop_platform_fee*$exchangerate;
			$postdata["paypalmail"]='';
			
			$postdata['platformID']  = $rshop[0]['platfrom'];//平台
			$postdata['moneyrate']  = $exchangerate;//汇率

			$this->db1->trans_begin();	//事务开始
			$this->db1->insert("db_order_list",$postdata);
			$orderID = $this->db1->insert_id();


			$weight = 0;
			$rsdbsell = $this->db2->get_where("db_wish_order_sell"," order_id='".$rs["order_id"]."'")->result_array();
			$rsdbsell = $rsdbsell[0];

				unset($goods_name);
					$rgoods = $this->db1->get_where("db_goods","goods_sku='{$rsdbsell[goods_sn]}' or cognatelist like '%,{$rsdbsell[goods_sn]},%'")->result_array(); 
					if(empty($rgoods))
					{
						$Status=7;
						$goods_id = 0;
						$sweight = 0;
						$weight = 0;
						$goods_sn = $rsdbsell['goods_sn'];
						$costprice = 0;
					}else{
						$factorycode = $this->factorycode();
						$Status=2;
						$goods_id = $rgoods[0]["goods_id"];
						$sweight = $rsdbsell["goods_number"] * $rgoods[0]["g_weight"];
						$weight = $weight+$sweight;
						$goods_sn = $rgoods[0]["goods_sku"];
						if(is_numeric($goods_sn) && preg_match('|^\d{8}$|',$goods_sn))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($goods_sn,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
						}
						$goods_sn = $rgoods[0]["goods_sku"];
						$goods_name =  $rgoods[0]["goods_name"];
					}
					
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = $goods_name?$goods_name:addslashes($rsdbsell['goods_name']);
					$postsell["goods_sn"] = $goods_sn;
					$postsell["costprice"] = $costprice;
					$postsell["goods_number"] = $rsdbsell["goods_number"];
					$postsell["goods_price"] = $rsdbsell["goods_price"]*$exchangerate;
					$postsell["goods_weight"]=$weight;
					$postsell["product_link"]=$rsdbsell["product_link"];
					$postsell["goods_amount"] = $rsdbsell["goods_price"]*$rsdbsell["goods_number"]*$exchangerate;
					$postsell["originsellprice"] = $rsdbsell["goods_price"];
					$postsell["originsku"] = $rsdbsell["originsku"];
					$this->db1->insert("db_order_sell",$postsell);
					if($goods_id==0)
					{
						$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
					if($weight)
					{
						$this->db1->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
					}
		
					$imgdata["goods_id"] = $orderID;	//订单ID
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 0;
					$imgdata["types"] = 3;
					$imgdata["content"] = 'wish接口自动新增订单,交易ID='.$rs["tradeid"];
					$imgdata["createUser"] ='auto';
					$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));

					$this->db2->update("db_wish_order_list",array("syntype"=>2,"descr"=>'已同步系统成功'),"tradeid='".$rs["tradeid"]."' AND order_id ='".$rs["order_id"]."'");

					if ($this->db1->trans_status() === FALSE)
					{
						$this->db1->trans_rollback();
					}
					else
					{
						$this->db1->trans_commit();
					}

			$this->getinsertdata();
	}
	

	/*****读取Wish退款信息****/
	function getinsertrefunddata()
	{
		$this->db2->limit(1);
		$row = $this->db2->get_where("db_wish_refund","syntype=1  ")->result_array();
		
		if(count($row)==0)
		{
			return false;
		}
		$rs = $row[0];
		$rorder = $this->db1->get_where("db_wish_refund","tradeid='".$rs["tradeid"]."' AND shopid='".$rs["shopid"]."'")->result_array();
		if($rorder[0]["order_number"])
		{
			$this->db2->update("db_wish_refund",array("syntype"=>2,"descr"=>'已同步系统成功'),"tradeid='".$rs["tradeid"]."' ");
			return $this->getinsertrefunddata();
		}
		
			$order=$this->db1->get_where("db_order_list","tradeid='".$rs["tradeid"]."'")->result_array();
			if($order[0]["order_id"]>0){
				$exchangerate=$order[0]["moneyrate"]; 
				$postdata="";
				$postdata["order_number"] =$rs["order_sn"];
				$postdata["shopid"] = $rs["shopid"];
				$postdata["shopname"] = $rs["shopname"];
				$postdata["moneytype"] ='USD';
				$postdata["tradeid"] = $rs["tradeid"];
				$postdata["add_time"] = $rs['add_time'];
				$postdata["Refund_Responsibility"] =$rs['Refund_Responsibility'];
				$postdata["Refund_Amount"] = $rs['Refund_Amount'];
				$postdata["Refund_Date"] = $rs['Refund_Date'];
				$postdata["Refund_Reason"] =$rs["Refund_Reason"];
				$postdata['moneyrate']  = $exchangerate;//汇率
				$postdata["Refund_Amount_Rmb"] = $rs['Refund_Amount']*$exchangerate;
				$postdata["order_id"] =$order[0]["order_id"];
				$postdata["order_sn"] =$order[0]["order_sn"];
				$postdata["instime"] = time();
				$sell=$this->db2->get_where("db_wish_refund_sell","order_id='".$rs["order_id"]."'")->result_array();
				$postdata["goods_sn"] =$sell[0]["goods_sn"];
				$rgoods = $this->db1->get_where("db_goods","goods_sku='{$sell[0][goods_sn]}' or cognatelist like '%,{$sell[0][goods_sn]},%'")->result_array(); 
				$postdata["goods_id"] =$rgoods[0]["goods_id"]?$rgoods[0]["goods_id"]:0;
				$this->db1->insert("db_wish_refund",$postdata);
				$this->db2->update("db_wish_refund",array("syntype"=>2,"descr"=>'已同步系统成功'),"tradeid='".$rs["tradeid"]."' AND order_id ='".$rs["order_id"]."'");
			}else{
				$this->db2->update("db_wish_refund",array("syntype"=>3,"descr"=>'已同步,不存在的订单'),"tradeid='".$rs["tradeid"]."' AND order_id ='".$rs["order_id"]."'");
			}



			
			return $this->getinsertrefunddata();
	}
	

	
	public function wishreturn()
	{     
		//删除两个小时未下载成功的数据
         // date_default_timezone_set("Europe/London");
         // $deltime=date('Y-m-d H:i:s',time()-7200);
         $delspl="DELETE FROM db_wish_download WHERE code = 1016 ;";
         $this->db2->query($delspl);
         
         //物流回传的，让物流回传的重新更新一下
         $sqlup="UPDATE db_wish_update SET isupdate=1 WHERE isupdate=3 AND message = '';";
         $this->db2->query($sqlup);

		$wisharr=$this->db1->get_where("d_shop","platfromname='Wish' AND amazonkey is not null and agent_visit = 1")->result_array();
		foreach($wisharr as $key=>$value)
		{
			$shopname=$value['name'];
			$shopid=$value['id'];
			$listrow= $this->db1->get_where("db_order_list","shopname='{$shopname}'  and is_update_platform='0' and (order_status='4' or order_status = '5')  AND shipping_number !='' ")->result_array();

			//$listrow= $this->db1->get_where("db_order_list","shopname='{$shopname}'  and is_update_platform='0' and shipping_number !='' ")->result_array();
			if(count($listrow)>0)
			{
				foreach($listrow as $key=>$rs)
				{
					if($rs["shipping_id"]==0 && $rs["shipping_name"])
					{
						$shippingrow=$this->db1->get_where("db_order_express","name='". $rs["shipping_name"]."'")->result_array();
						$wish_express = $shippingrow[0]["wish_express"];
					}else{
						$shippingrow=$this->db1->get_where("db_order_express","id='". $rs["shipping_id"]."'")->result_array();
						$wish_express = $shippingrow[0]["wish_express"];
					}
					
					
					$post="";
					$post["order_id"] = $rs["order_sn"];
					$post["tradeid"] = $rs["tradeid"];
					$post["shipping_id"] = $rs["shipping_id"];
					$post["shipping_number"] = $rs["shipping_number"];
					$post["shipping_name"] = $wish_express?$wish_express:'CNEExpress';
					$post["shopid"] = $rs["shopid"];
					$post["shopname"] = $rs["shopname"];
					$post["isupdate"] = 1;
					$post["updatetime"] = date("Y-m-d H:i:s");
					$post["message"] ="等待更新到wish平台";
					$this->db2->insert("db_wish_update",$post);


					$this->db1->update("db_order_list",array("is_update_platform"=>'1'),"order_id=".$rs['order_id']);	//不再更新
					$log='';
					$log['orderId']=$rs['order_id'];
					$log['updateTime']=date('Y-m-d H:i:s');
					$log['shippingName']=$wish_express;
					$log['shippingNumber']=$rs["shipping_number"];
					$log['types']='wish';
					$log['content']='自动同步物流信息'.$response;
					$this->db1->insert("db_onlineshop_log",$log);
					$imgdata = "";
					$imgdata["goods_id"] = $rs['order_id'];	//订单ID
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 0;
					$imgdata["types"] = 3;
					$imgdata["content"] = '自动同步物流信息,物流名称'.$wish_express.'物流单号='.$rs["shipping_number"];
					$imgdata["createUser"] ='auto';
					$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
				}
			}
		}
		
	}




	public function factorycode()
	{
		$rsdb = $this->db1->get_where("db_factory","code >0")->result_array();
		foreach($rsdb as $key =>$rs)
		{
			$factorycode[] = $rs["code"];	//工厂编号
		}
		return $factorycode;
	}
























}


?>